/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.tln.sys.user.service.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tln.sys.user.dao.UserDao;
import com.tln.sys.user.model.User;
import com.tln.sys.user.service.UserService;
import com.xjj.core.modules.dao.template.DbUtilsTemplate;
import com.xjj.core.modules.orm.Finder;
import com.xjj.core.modules.orm.Page;

import java.util.List;
import java.util.Map;

/**
 * Default implementation of the {@link UserService} interface.  This service implements
 * operations related to User data.
 */
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
	
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); 

    private UserDao userDao;
    
    
    //private CompanyDao companyDao;
    
    @Autowired
	private DbUtilsTemplate dbUtilsTemplate;

    
    
    /*@Autowired
    public void setCompanyDao(CompanyDao companyDao) {
		this.companyDao = companyDao;
	}*/


    @Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User getCurrentUser() {
    	/*logger.info("getCurrentUser--------------------");
    	//logger.info("companyDao--------------------"+companyDao);
    	logger.info("getCurrentUser--------------------"+SecurityUtils.class);
    	logger.info("getSubject--"+SecurityUtils.getSubject());
    	logger.info("getPrincipal--"+SecurityUtils.getSubject().getPrincipal());*/
        final Long currentUserId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info("currentUserId--------------------"+currentUserId);
        if( currentUserId != null ) {
            return getUser(currentUserId);
        } else {
            return null;
        }
    }

    public void saveUser(User user) {
        /*User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword( new Sha256Hash(password).toHex() );*/
        userDao.save(user);
    }

    public List<User> getAllUsers() {
    	//logger.info("userDao......."+userDAO);
    	//logger.info("companyDao--------------------"+companyDao);
    	//logger.info("dbUtilsTemplate......."+dbUtilsTemplate);
    	/*Object[][] params1 = new Object[][] { { 1, "user", "all users."}};
    	Object[][] params2 = new Object[][] { { 2, "admin", "site admins"}};
    	Object[][] params3 = new Object[][] { { 2, "user:*"}};
    	Object[][] params4 = new Object[][] { { 1, "admin", "sample@shiro.apache.org", ""+new Sha256Hash("admin").toHex() }};
    	Object[][] params5 = new Object[][] { { 1, 2}};
	    int[] result = 
	    	dbUtilsTemplate.batch("insert into roles values (?, ?, ?)", params1);
	    int[] result2 = 
	    	dbUtilsTemplate.batch("insert into roles values (?, ?, ?)", params2);
	    logger.info("result2--- "+result2.length);
	    int[] result3 = 
	    	dbUtilsTemplate.batch("insert into roles_permissions values (?, ?)", params3);
	    logger.info("result2--- "+result3.length);
	    int[] result4 = 
	    	dbUtilsTemplate.batch("insert into users(id,username,email,password) values (?, ?, ?, ?)", params4);
	    logger.info("result2--- "+result4.length);
	    int[] result5 = 
	    	dbUtilsTemplate.batch("insert into users_roles values (?, ?)", params5);
	    logger.info("result2--- "+result5.length);*/
	    
	   
	    
        return userDao.getAllUsers();
    }

    public User getUser(Long userId) {
        return userDao.getUser(userId);
    }

    public void deleteUser(Long userId) {
    	userDao.delete( userId );
    }

    public void updateUser(User user) {
    	userDao.update( user );
    }

    @Transactional(readOnly=true)
	public Page<User> getAllUserByHql(Map map, int pageNo, int pageSize) {
		String menuName = (String)map.get("menuName");
		Finder f = Finder.create("select bean.id from User bean where 1=1");
		f.append(" order by bean.id desc");
		if (StringUtils.isNotEmpty(menuName)) {
			f.append(" and bean.menuName like :menuName").setParam("menuName","%" + menuName + "%" );
		}
		//this.logger.info("hql------ "+f.getOrigHql());
		Page<User> page = this.userDao.findByFinder(f, pageNo, pageSize);
		List<User> list = page.getResult();
		//Long date = System.currentTimeMillis();
		//String idString = list.toString();
		String idString = StringUtils.join(list, ",");//这种转换也非常不错
		//logger.info("idTestString:  "+idTestString);
		//Long date1 = System.currentTimeMillis();
		//logger.info("字符串转换时间 --- "+(date1-date));
		//idString = idString.substring(1, idString.length()-1);
		logger.info("idString:  "+idString);
		
		//Long date00 = System.currentTimeMillis();
		
		String hql = "select bean from User bean where 1=1";
		if (StringUtils.isNotEmpty(idString)) {
			hql += " and id in ("+idString+")";
		}
		hql += " order by bean.id desc";
		List<User> resultList = this.userDao.find(hql);
		//Long date11 = System.currentTimeMillis();
		//logger.info("in 查询date --- "+(date11-date00));
		page.setResult(resultList);
		return page;
	}

}
